package blue.http.internal.core.mapping;

import blue.http.core.filter.WebSocketFilter;
import blue.http.core.message.WebSocketRequest;
import blue.http.core.message.WebSocketResponse;
import blue.http.internal.core.handler.HandlerChain;
import blue.http.internal.core.handler.WebSocketHandlerChain;
import blue.http.internal.core.parser.FilterConfigCache;
import blue.http.internal.core.parser.ParserFactory;
import blue.http.internal.core.parser.WebSocketConfigCache;
import blue.http.internal.core.parser.WebSocketMethodResult;
import blue.http.internal.core.parser.WebSocketUrlKey;

import java.util.List;

/**
 * @author Jin Zheng
 * @since 1.0 2020-01-07
 */
public class WebSocketHandlerMapping implements HandlerMapping<WebSocketRequest, WebSocketResponse> {
	private final WebSocketConfigCache webSocketConfigCache;
	private final FilterConfigCache filterCache;

	public WebSocketHandlerMapping(ParserFactory parserFactory) {
		this.webSocketConfigCache = parserFactory.getWebSocketConfigCache();
		this.filterCache = parserFactory.getFilterConfigCache();
	}

	@Override
	public boolean accepted(Object request) {
		return request != null && request instanceof WebSocketRequest;
	}

	@Override
	public HandlerChain getHandlerChain(WebSocketRequest request) {
		WebSocketUrlKey key = new WebSocketUrlKey(request.getUrl());
		WebSocketMethodResult result = webSocketConfigCache.getConfig(key);
		if (result == null) {
			return null;
		}

		List<WebSocketFilter> filterList = filterCache.matchWebSocketFilter(request.getUrl());
		var chain = new WebSocketHandlerChain(result, filterList);
		return chain;
	}
}
